<template>
  <!-- 优惠价格 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item label="商品分类">
        <el-tree-select
          v-model="query.gtCode"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择商品分类',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: gtCodeMap,
          }"
          @node-click="gtCodeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称">
        <el-select v-model="query.goodsCode" placeholder="请选择">
          <el-option
            v-for="item in goodsCodeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单来源">
        <el-select v-model="query.orderSource" placeholder="请选择">
          <el-option
            v-for="item in orderSourceMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户性质">
        <el-select v-model="query.customerQuality" placeholder="请选择">
          <el-option
            v-for="item in csmQualityMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="组织机构" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="客户类型">
        <el-select v-model="query.customerType" placeholder="请选择">
          <el-option
            v-for="(value, key) in csmTypeMap"
            :key="key"
            :label="value.desc"
            :value="value.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效期(起)">
        <el-date-picker
          v-model="query.startDt"
          type="date"
          placeholder="选择日期时间"
          @change="toDate()"
        />
      </el-form-item>
      <el-form-item label="有效期(止)">
        <el-date-picker
          v-model="query.endDt"
          type="date"
          format="yyyy-mm-dd HH:mm:ss"
          placeholder="选择日期时间"
          @change="toDate()"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>

    <div style="margin-bottom: 20px;">
      <div>
        <el-button
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="openDiscountsAdd"
        >新增</el-button>
      </div>
    </div>

    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <discounts
      ref="discounts"
      :csm-type-map="csmTypeMap"
      :order-source-map="orderSourceMap"
      :tree-data="treeData"
      :csm-quality-map="csmQualityMap.slice(1, csmQualityMap.length)"
      :gt-code-map="gtCodeMap"
      @refresh="search"
      @getGoodData="getGoodData"
    />
  </div>
</template>

<script>
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import Discounts from './components/Discounts'
  import {
    goodsTypeQueryList,
    priceDiscountList,
    priceDiscountDelete,
    goodTypeById,
    queryMap
  } from '@/api'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'discountPriceManage',
    components: {
      Discounts
    },
    data() {
      return {
        orderSourceMap: [],
        csmQualityMap: [
          { value: 0, desc: '不限' },
          { value: 1, desc: '普通' },
          { value: 2, desc: '特殊' },
          { value: 3, desc: '白金' },
          { value: 4, desc: '钻石' }
        ],
        csmTypeMap: [],
        goodsCodeMap: [],
        gtCodeMap: [],
        treeData: [],
        query: {
          gtCode: '',
          goodsCode: '',
          orderSource: '',
          customerQuality: 0,
          orgSNNo: '',
          customerType: '',
          startDt: '',
          endDt: ''
        },
        actionColWidth: 80,
        tableData: {
          total: 0,
          column: [
            {
              type: 'index',
              width: 30
            },
            {
              prop: 'gtName',
              label: '商品分类',
              width: 180
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 110,
              render: (h, { row }) => <span>{this.productName(row)}</span>
            },
            {
              prop: 'orderSource',
              label: '订单来源',
              width: 110,
              render: (h, { row }) => <span>{this.orderSourceMap.find(v => row.orderSource === v.value).desc}</span>
            },
            {
              prop: 'customerType',
              label: '客户类型',
              width: 110,
              render: (h, { row }) => <span>{this.csmTypeMap.find(v => row.customerType === v.value).desc}</span>
            },
            {
              prop: 'customerQuality',
              label: '客户性质',
              width: 110,
              render: (h, { row }) => <span>{this.csmQualityFormat(row)}</span>
            },
            {
              prop: 'orgName',
              label: '优惠有效范围',
              width: 200
            },
            {
              prop: 'price',
              label: '优惠价格',
              width: 110,
              render: (h, { row }) => <span>{this.priceFormat(row)}</span>
            },
            {
              prop: 'startDt',
              label: '有效期(起)',
              width: 200
            },
            {
              prop: 'endDt',
              label: '有效期(止)',
              width: 200
            },
            {
              label: '操作',
              align: 'center',
              fixed: 'right',
              width: 80,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' onClick={() => this.openDiscounts(row, $index)}>
                      编辑
                    </el-link>
                    <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>
                      作废
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      column() {
        return [
          {
            type: 'index',
            width: 30
          },
          {
            prop: 'gtName',
            label: '商品分类',
            width: 180
          },
          {
            prop: 'goodsName',
            label: '商品名称',
            width: 110,
            render: (h, { row }) => <span>{this.productName(row)}</span>
          },
          {
            prop: 'orderSource',
            label: '订单来源',
            width: 110,
            render: (h, { row }) => (
            <span>
              {(row.orderSource || row.orderSource === 0) &&
                formatColumnMap(this.orderSourceMap, 'value', row.orderSource, 'desc')}
            </span>
          )
          },
          {
            prop: 'customerType',
            label: '客户类型',
            width: 110,
            render: (h, { row }) => (
            <span>
              {(row.customerType || row.customerType === 0) &&
                formatColumnMap(this.csmTypeMap, 'value', row.customerType, 'desc')}
            </span>
          )
          },
          {
            prop: 'customerQuality',
            label: '客户性质',
            width: 110,
            render: (h, { row }) => <span>{this.csmQualityFormat(row)}</span>
          },
          {
            prop: 'orgName',
            label: '优惠有效范围',
            width: 200
          },
          {
            prop: 'price',
            label: '优惠价格',
            width: 110,
            render: (h, { row }) => <span>{this.priceFormat(row)}</span>
          },
          {
            prop: 'startDt',
            label: '有效期(起)',
            width: 200
          },
          {
            prop: 'endDt',
            label: '有效期(止)',
            width: 200
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
              <div>
                <el-link size='mini' onClick={() => this.openDiscounts(row, $index)}>
                  编辑
                </el-link>
                <el-link size='mini' type='danger' onClick={() => this.del(row, $index)}>
                  作废
                </el-link>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
      await this.queryOptionsMap()
    },
    methods: {
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 时间冲突
      toDate() {
        const startDt = this.form.startDt
        const endDt = this.form.endDt
        if (endDt < startDt) {
          this.$confirm('起始日期不能大于结束日期', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {})
            .catch(() => {})
        }
      },

      // 客户性质
      csmQualityFormat(val) {
        let msg = '不限'
        if (val.customerQuality === 1) msg = '普通'
        else if (val.customerQuality === 2) msg = '特殊'
        else if (val.customerQuality === 3) msg = '白金'
        else if (val.customerQuality === 4) msg = '钻石'
        return msg
      },
      // 优惠价格
      priceFormat(val) {
        return `${val.price}元`
      },
      // 商品名称
      productName(val) {
        let msg = val.goodsName
        if (val.goodsName === null) msg = '不限'
        else if (val.goodsName === '') msg = '不限'
        else if (val.goodsName === undefined) msg = '不限'
        return msg
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      // 查询枚举
      async queryOptionsMap() {
        const [res1, res2, res3] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'OrderSource' }),
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          goodsTypeQueryList()
        ])
        this.orderSourceMap = res1.data //
        this.csmTypeMap = res2.data // 客户类型

        const data = res3.data.map((item) => ({
          label: item.gtName,
          ...item
        }))
        this.gtCodeMap = getTreeData(data) // 商品分类
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (!query.orderSource) query.orderSource = 0
        const { status, data } = await priceDiscountList(query)
        if (status === 200) {
          this.tableData.data = data.rows
          if (currentPage === 1) this.tableData.total = data.total
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 修改
      openDiscounts(row) {
        this.$refs.discounts.show('edit', row)
      },
      // 新增
      openDiscountsAdd() {
        this.$refs.discounts.show('add')
      },
      // 作废
      del(row) {
        this.$confirm('您确认要作废此优惠价格吗?', '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.delSubmit(row)
          })
          .catch(() => {})
      },
      async delSubmit(row) {
        const params = {
          priceId: row.priceId
        }
        const { status } = await priceDiscountDelete(params)
        if (status === 200) {
          this.$notify({
            title: '提示',
            message: '操作成功',
            type: 'success',
            duration: 2000
          })
          this.search()
        }
      },
      gtCodeChange(value) {
        this.query.gtCode = value.gtCode
        this.getGoodData(value.gtId)
      },
      async getGoodData(id) {
        const { status, data } = await goodTypeById({ gTypeId: id })
        if (status === 200) {
          this.goodsCodeMap = data.map((v) => {
            return {
              desc: v.goodsName,
              value: v.goodsId
            }
          })
        }
      }
    }
  }
</script>

<style lang="scss" scoped></style>
